require "common/Define"
require "framework/BaseController"
require "FairyGUI"

LoopListMain = BaseController:New({mControllerName = "LoopListMain"});

function LoopListMain.Main()
	-- body
	LoopListMain:Awake();
end

function LoopListMain:Awake()
	Application.targetFrameRate = 60;
	Stage.inst.onKeyDown:Add(self.OnKeyDown, self);

	-- attack pacakge, package in resource or assetbundle
	local packageName = "UI/LoopList";
	UIPackage.AddPackage(packageName);

	local componentName = "Main";
	self.mainComponent = UIPackage.CreateObject("LoopList", componentName).asCom;
	GRoot.inst:AddChild( self.mainComponent );

	--local go = GameObject();
	--local panel = go:AddComponent(typeof(UIPanel));
	--panel.container:AddChild(self.mainComponent);
	--GRoot.inst:AddChild( panel );

	-- self.mainComponent:SetSize(GRoot.inst.width, GRoot.inst.height);
	-- self.mainComponent:AddRelation(GRoot.inst, RelationType.Size);
	GRoot.inst:SetContentScaleFactor(1134, 640, FairyGUI.UIContentScaler.ScreenMatchMode.MatchWidthOrHeight);

	self:OnViewCreated(self.mainComponent);
end

function LoopListMain:InitView()
	self._list = self.mainComponent:GetChild("list").asList;
	self._list:SetVirtualAndLoop();

	self._list.itemRenderer = self.RenderListItem;
	self._list.numItems = 5;
	self._list.scrollPane.onScroll:Add(self.DoSpecialEffect, self);

	self:DoSpecialEffect();
end

function LoopListMain:DoSpecialEffect()
	print(self)
	local midX = self._list.scrollPane.posX + self._list.viewWidth / 2;
	local cnt = self._list.numChildren;
	for i=0, cnt-1, 1 do
		local obj = self._list:GetChildAt(i);
		local dist = Mathf.Abs(midX - obj.x - obj.width / 2);
		if (dist > obj.width) then
			obj:SetScale(1, 1);
		else
			local ss = 1 + (1 - dist / obj.width) * 0.24;
			obj:SetScale(ss, ss);
		end
	end

	self.mainComponent:GetChild("n3").text = "" .. ((self._list:GetFirstChildInView() + 1) % self._list.numItems);
end

function LoopListMain.RenderListItem(index, obj)
	local item = obj;
	item:SetPivot(0.5, 0.5);
	item.icon = UIPackage.GetItemURL("LoopList", "n" .. (index + 1));
end


function LoopListMain:OnKeyDown(context)
	if (context.inputEvent.keyCode == KeyCode.Escape) then
		Application.Quit();
	end
end